package com.quasar.hpatient.view.personal.historyRecord;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;

import com.alibaba.fastjson.JSON;
import com.change360.calendarview.CalendarDay;
import com.change360.calendarview.MaterialCalendarView;
import com.change360.calendarview.OnDateChangedListener;
import com.change360.calendarview.OnMonthChangedListener;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.custommodel.RecordState;
import com.quasar.hpatient.model.event.EventDecorator;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.medicalmodel.CalendarDataBean;
import com.quasar.hpatient.model.medicalmodel.DiagnoseListData;
import com.quasar.hpatient.model.medicalmodel.ListDiagnose;
import com.quasar.hpatient.model.medicalmodel.TestPresentationData;
import com.quasar.hpatient.onInterface.OnDiagnoseListListener;
import com.quasar.hpatient.presenter.LaboratoryDatePresenter;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.record.TestRecordActivity_;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * 化验报告日期界面
 */
@EActivity(R.layout.activity_laboratory_date)
public class LaboratoryDateActivity extends BaseActivity implements OnDiagnoseListListener
        , OnDateChangedListener, OnMonthChangedListener {

    private LaboratoryDatePresenter laboratoryDatePresenter;
    CalendarDay calendarDay;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd");

    @ViewById(R.id.calendarView)
    MaterialCalendarView calendarView;

    @AfterViews
    void init() {
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        List<String> lfdays = new ArrayList<>();
        lfdays.add("ss");
        calendarView.setCurrentDate(Calendar.getInstance());
        calendarView.setCurrentDate(new Date());
        calendarView.setSelectedDate(new Date());
        calendarView.setOnDateChangedListener(this);
        calendarView.setOnMonthChangedListener(this);
        calendarView.setMaximumDate(new Date());
        calendarDay = new CalendarDay();
    }


    @Override
    protected void initData() {
        laboratoryDatePresenter = new LaboratoryDatePresenter(this);
    }



    @Override
    public void onDateChanged(MaterialCalendarView widget, CalendarDay date) {
        //跳转到添加化验单界面
        TestRecordActivity_.intent(this).TestTime(formatTime.format(date.getDate())).start();
    }

    @Override
    public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
        laboratoryDatePresenter.GetPatientInspectionListAndDiagnoseData(fastMoth(date), lastMoth(date));
    }



    //获取当前月第一天
    public String fastMoth(CalendarDay date) {
        Calendar c = date.getCalendar();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());

        return first;
    }

    //获取当月最后一天
    public String lastMoth(CalendarDay date) {
        Calendar cale = date.getCalendar();
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
        return format.format(cale.getTime());
    }


    @Override
    public void onLaboratorySuccess(AnotherResult<TestPresentationData> PresentationInterface) {

    }

    @Override
    public void onViewError(String msg) {

        if(msg!=null){
            msg(msg);
        }
    }

    @Override
    public void onViewRefreshUI() {

    }

    @Override
    public void onDiagnoseSuccess(AnotherResult<DiagnoseListData> DiagnoseInterface) {


    }

    @Override
    public void NewTestSuccess(ListDiagnose listDiagnose) {
        if (listDiagnose != null) {
            Map<String, CalendarDataBean.CalendarDataItemBean> map = new HashMap<>();
            //判断诊是否存在
            if (listDiagnose.getListDiagnose() != null) {
                for (int i = 0; i < listDiagnose.getListDiagnose().size(); i++) {
                    map.put(listDiagnose.getListDiagnose().get(i).getCheckdatetime().substring(0, 10),
                            new CalendarDataBean.CalendarDataItemBean(listDiagnose.getListDiagnose().get(i).getStatus() + "", "ListDiagnose"));
                }
            }
            //判断是否存在化验单
            if (listDiagnose.getListInspectionIndex() != null) {
                for (int i = 0; i < listDiagnose.getListInspectionIndex().size(); i++) {
                    map.put(listDiagnose.getListInspectionIndex().get(i).getTesttime().substring(0, 10),
                            new CalendarDataBean.CalendarDataItemBean(listDiagnose.getListInspectionIndex().get(i).getStatus() + "", "ListInspectionIndex"));
                }
            }
            Map<String, List<CalendarDataBean.CalendarDataItemBean>> map1 = new HashMap<>();
            for (String time : map.keySet()) {
                List<CalendarDataBean.CalendarDataItemBean> lifecycleTestItems = new ArrayList<>();
                //诊断
                for (int i = 0; i < listDiagnose.getListDiagnose().size(); i++) {
                    if (time.equals(listDiagnose.getListDiagnose().get(i).getCheckdatetime().substring(0, 10))) {
                        lifecycleTestItems.add(new CalendarDataBean.CalendarDataItemBean(listDiagnose.getListDiagnose().get(i).getStatus() + "", "ListDiagnose"));
                    }
                    map1.put(time, lifecycleTestItems);
                }
                //化验单
                for (int i = 0; i < listDiagnose.getListInspectionIndex().size(); i++) {
                    if (time.equals(listDiagnose.getListInspectionIndex().get(i).getTesttime().substring(0, 10))) {
                        lifecycleTestItems.add(new CalendarDataBean.CalendarDataItemBean(listDiagnose.getListInspectionIndex().get(i).getStatus() + "", "ListInspectionIndex"));
                    }
                    map1.put(time, lifecycleTestItems);
                }
            }

            List<CalendarDataBean> calendarDataBeen = new ArrayList<>();
            for (Map.Entry<String, List<CalendarDataBean.CalendarDataItemBean>> entry : map1.entrySet()) {
                CalendarDataBean a = new CalendarDataBean();
                a.setTime(entry.getKey());
                a.setCalendarDataBean(entry.getValue());
                calendarDataBeen.add(a);
            }
            String json = JSON.toJSONString(calendarDataBeen);
            ViseLog.d(json);
            new ApiSimulator(calendarDataBeen).executeOnExecutor(Executors.newSingleThreadExecutor(), calendarDay);
        }

    }

    private class ApiSimulator extends AsyncTask<CalendarDay, Void, List<RecordState>> {

        private List<CalendarDataBean> dailyRecordDataList;

        ArrayList<RecordState> csdates = new ArrayList<>(); //异常
        ArrayList<RecordState> lfdates = new ArrayList<>(); //正常
        ArrayList<RecordState> regular = new ArrayList<>(); //正常诊断
        ArrayList<RecordState> abnormal = new ArrayList<>();//异常诊断

        public ApiSimulator(List<CalendarDataBean> dailyRecordDataList) {
            this.dailyRecordDataList = dailyRecordDataList;
        }

        @Override
        protected List<RecordState> doInBackground(CalendarDay... voids) {

            ArrayList<RecordState> dates = new ArrayList<>();

            for (int i = 0; i < dailyRecordDataList.size(); i++) {
                RecordState recordState = new RecordState();
                recordState.drawable = R.mipmap.normal;
                Date de = null;
                try {
                    de = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar c = Calendar.getInstance();
                c.setTime(de);
                recordState.calendarDay = new CalendarDay(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                dates.add(recordState);

                if (dailyRecordDataList.get(i).getCalendarDataBean() != null) {

                    if (dailyRecordDataList.get(i).getCalendarDataBean().size() > 1) {

                        for (int a = 0; a < dailyRecordDataList.get(i).getCalendarDataBean().size(); a++) {


                            if (dailyRecordDataList.get(i).getCalendarDataBean().get(a).getName() != null) {
                                ViseLog.d("dailyRecordDataList");
                                if (dailyRecordDataList.get(i).getCalendarDataBean().get(a).getName().equals("ListInspectionIndex")) {
                                    ViseLog.d("ListInspectionIndex");
                                    if (dailyRecordDataList.get(i).getCalendarDataBean().get(a).getDiaStatus().equals("0") ||
                                            dailyRecordDataList.get(i).getCalendarDataBean().get(a).getDiaStatus().equals("2")) {
                                        ViseLog.d("ListInspectionIndex：1");
                                        RecordState xxxx = new RecordState();
                                        Date des = null;
                                        try {
                                            des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        Calendar b = Calendar.getInstance();
                                        b.setTime(des);
                                        xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
                                        regular.add(xxxx);
                                        continue;
                                    } else if (dailyRecordDataList.get(i).getCalendarDataBean().get(a).getDiaStatus().equals("1")) {
                                        ViseLog.d("ListInspectionIndex：2");
                                        RecordState xxxx = new RecordState();
                                        Date des = null;
                                        try {
                                            des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        Calendar b = Calendar.getInstance();
                                        b.setTime(des);
                                        xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
                                        abnormal.add(xxxx);
                                        continue;

                                    }
                                }
                            }
                        }
                    } else {
                        if (dailyRecordDataList.get(i).getCalendarDataBean().get(0).getName() != null) {
                            //证明是化验单
                            if (dailyRecordDataList.get(i).getCalendarDataBean().get(0).getName().equals("ListInspectionIndex")) {
                                if (dailyRecordDataList.get(i).getCalendarDataBean().get(0).getDiaStatus().equals("1")) {
                                    ViseLog.d("异常的数据" + dailyRecordDataList.get(i).getTime() + " 00:00:00" + "数据的长度" + dailyRecordDataList.size());
                                    RecordState xxxx = new RecordState();
                                    Date des = null;
                                    try {
                                        des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    Calendar b = Calendar.getInstance();
                                    b.setTime(des);
                                    xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
                                    lfdates.add(xxxx);
                                    continue;
                                } else {
                                    ViseLog.d("正常的数据" + dailyRecordDataList.get(i).getTime() + " 00:00:00" + "数据的长度" + dailyRecordDataList.size());
                                    RecordState xxxx = new RecordState();
                                    Date des = null;
                                    try {
                                        des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    Calendar b = Calendar.getInstance();
                                    b.setTime(des);
                                    xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
                                    csdates.add(xxxx);

                                    continue;
                                }
                            }
//                            else {
//                                if (dailyRecordDataList.get(i).getCalendarDataBean().get(0).getDiaStatus().equals("1")) {
//                                    ViseLog.d("异常的数据" + dailyRecordDataList.get(i).getTime() + " 00:00:00" + "数据的长度" + dailyRecordDataList.size());
//                                    RecordState xxxx = new RecordState();
//                                    Date des = null;
//                                    try {
//                                        des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    Calendar b = Calendar.getInstance();
//                                    b.setTime(des);
//                                    xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
//                                    csdates.add(xxxx);
//                                    continue;
//                                } else {
//                                    ViseLog.d("正常的数据" + dailyRecordDataList.get(i).getTime() + " 00:00:00" + "数据的长度" + dailyRecordDataList.size());
//                                    RecordState xxxx = new RecordState();
//                                    Date des = null;
//                                    try {
//                                        des = TimeZoneUtil.sdf.parse(dailyRecordDataList.get(i).getTime() + " 00:00:00");
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    Calendar b = Calendar.getInstance();
//                                    b.setTime(des);
//                                    xxxx.calendarDay = new CalendarDay(b.get(Calendar.YEAR), b.get(Calendar.MONTH), b.get(Calendar.DAY_OF_MONTH));
//                                    lfdates.add(xxxx);
//                                    continue;
//                                }
//                            }
                        }
                    }
                }
            }
            return dates;
        }

        @Override
        protected void onPostExecute(List<RecordState> calendarDays) {
            super.onPostExecute(calendarDays);
            List<CalendarDay> days = new ArrayList<>();

            for (int i = 0; i < calendarDays.size(); i++) {
                RecordState state = calendarDays.get(i);
                days.add(state.calendarDay);
            }
            Drawable drawable = getResources().getDrawable(R.mipmap.normal);
            calendarView.addDecorator(new EventDecorator(drawable, days));

            if (csdates != null) {
                List<CalendarDay> csdays = new ArrayList<>();
                for (int i = 0; i < csdates.size(); i++) {
                    RecordState state = csdates.get(i);
                    csdays.add(state.calendarDay);
                }
                calendarView.addDecorator(new EventDecorator(getResources().getDrawable(R.mipmap.normal), csdays));
            }

            if (lfdates != null) {
                List<CalendarDay> lfdays = new ArrayList<>();
                for (int i = 0; i < lfdates.size(); i++) {
                    RecordState state = lfdates.get(i);
                    lfdays.add(state.calendarDay);
                }
                calendarView.addDecorator(new EventDecorator(getResources().getDrawable(R.mipmap.abnormal), lfdays));


            }

            if (regular != null) {
                List<CalendarDay> twos = new ArrayList<>();
                for (int i = 0; i < regular.size(); i++) {
                    RecordState state = regular.get(i);
                    twos.add(state.calendarDay);
                }
                calendarView.addDecorator(new EventDecorator(getResources().getDrawable(R.mipmap.nopicz), twos));
            }

            if (abnormal != null) {
                List<CalendarDay> abnormals = new ArrayList<>();
                for (int i = 0; i < abnormal.size(); i++) {
                    RecordState state = abnormal.get(i);
                    abnormals.add(state.calendarDay);
                }
                calendarView.addDecorator(new EventDecorator(getResources().getDrawable(R.mipmap.abnormal123), abnormals));
            }

        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        laboratoryDatePresenter.GetPatientInspectionListAndDiagnoseData(fastMoth(calendarDay), format.format(new Date()));
    }
}
